import 'dart:ffi';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import '../utils/mock_data.dart';

class ImageListPage extends StatefulWidget {
  const ImageListPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _ImageListPageState();
  }
}

class _ImageListPageState extends State<ImageListPage> {
  List<Map<String, Object>> listData = [];
  int _currentPage = 1;
  static const int PAGE_SIZE = 10;
  late EasyRefreshController _controller;

  @override
  void initState() {
    super.initState();
    _onRefresh();
    _controller = EasyRefreshController();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Flutter 图文并茂列表完整实现"),
      ),
      body: EasyRefresh(
        controller: _controller,
        onRefresh: () async {
          print('onRefresh====');
          await _onRefresh();
          _controller.finishRefresh();
        },
        onLoad: () async {
          print('onLoad====');
          await _onLoad();
          _controller.finishRefresh();
        },
        child: ListView.builder(
            itemCount: listData.length,
            itemBuilder: (BuildContext context, int index) {
              return DynamicItem(
                imagePath: listData[index]['imageUrl'].toString(),
                title: listData[index]['title'].toString(),
                viewCount: listData[index]['viewCount'].toString(),
              );
            }),
      ),
    );
  }

  _onLoad() async {
    print('_onLoad========');
    _currentPage += 1;
    await _requestData(false);
  }

  _onRefresh() async {
    print('_onRefresh11========');
    _currentPage = 1;
    await _requestData(true);
  }

  _requestData(clear) async {
    List<Map<String, Object>> newList =
        await DynamicMockData.list(_currentPage, PAGE_SIZE);
    setState(() {
      if (clear) listData = [];
      listData += newList;
    });
  }
}

class DynamicItem extends StatelessWidget {
  final String title;
  final String imagePath;
  final String viewCount;

  const DynamicItem(
      {super.key,
      required this.imagePath,
      required this.title,
      required this.viewCount});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          print("onTap");
          ScaffoldMessenger.of(context)
              .showSnackBar(SnackBar(content: Text(title)));
        },
        child: Container(
            padding: const EdgeInsets.all(10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _generateLeftLayout(context),
                Expanded(child: _generateRightLayout())
              ],
            )));
  }

  Widget _generateLeftLayout(context) {
    return SizedBox(
        width: 100,
        height: 100,
        child: CachedNetworkImage(
          imageUrl: imagePath,
          progressIndicatorBuilder: (context, url, downloadProgress) =>
              LinearProgressIndicator(value: downloadProgress.progress),
          errorWidget: (context, url, error) =>
              Image.asset('images/avatar.png'),
          width: MediaQuery.of(context).size.width,
          fit: BoxFit.fill,
          // fit: BoxFit.cover,
        ));
  }

  Widget _generateRightLayout() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _generateRightLayoutTitle(),
        _generateRightLayoutContent(),
      ],
    );
  }

  Widget _generateRightLayoutTitle() {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 5, 0, 0),
      child: Text(
        title,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
      ),
    );
  }

  Widget _generateRightLayoutContent() {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 30, 0, 0),
      child: Row(
        children: [
          const Icon(
            Icons.remove_red_eye_outlined,
            size: 15,
            color: Colors.grey,
          ),
          const SizedBox(
            width: 10,
          ),
          Text(
            viewCount,
            style: const TextStyle(color: Colors.blueGrey),
          )
        ],
      ),
    );
  }
}
